package com.example.administrator.ttphonehelper.process;

import android.app.ActivityManager;
import android.content.Context;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageManager;
import android.graphics.drawable.Drawable;

import com.example.administrator.ttphonehelper.bean.ProcessBean;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by Administrator on 2016/4/14 0014.
 */
public class ProcessManager {
    private static ActivityManager mActivityManager;
    private static ProcessManager mProcessManager;
    //包管理器
    private static PackageManager mPackageManager;
    private static Context mContext;
    private static List<ProcessBean> mList ;
    //单例模式
    private ProcessManager(){};
    //得到ProcessManager实例,此处的上下文请传全局上下文，否则Activity无法销毁，可能导致OOM异常
    public static ProcessManager getInstance(Context context){
        if(mProcessManager==null){
            mProcessManager = new ProcessManager();
            mContext = context;
            //进程管理器
            mActivityManager = (ActivityManager) mContext.getSystemService(Context.ACTIVITY_SERVICE);
            //包管理器
            mPackageManager = mContext.getPackageManager();
        }
        return mProcessManager;
    }
    //得到正在运行的进程
    public List<ProcessBean> getProcess(){
        //创建进程的容器
        mList = new ArrayList<>();


        //得到所有运行的进程
        List<ActivityManager.RunningAppProcessInfo> runList = mActivityManager.getRunningAppProcesses();
        for (ActivityManager.RunningAppProcessInfo proc: runList) {
            try {
                ApplicationInfo appInfo = mPackageManager.getApplicationInfo(proc.processName, 0);
                //得到名字
                String name = appInfo.loadLabel(mPackageManager).toString();
                //得到Icon
                Drawable icon = appInfo.loadIcon(mPackageManager);

                //将得到的进程存入List
                mList.add(new ProcessBean(name,icon));

            } catch (PackageManager.NameNotFoundException e) {
                e.printStackTrace();
            }
        }
        return mList;
    }
}
